<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import request from "./request/request";

import { storeToRefs } from 'pinia';
import { useUsersStore } from "./store/user";
const store = useUsersStore();
// 当仅使用 store 中的状态但不调用任何操作时，这很有用 from Pinia官网
const { keywords } = storeToRefs(store);

const dialogUserVisible = ref(false)
const dialogRegisterVisible = ref(false)
const userId = ref(111)

const userIdForVModel = ref(userId.value)

onMounted(() => {
  console.log('in root App / mounted');

  store.keywords = ""
  store.needForceRefresh = false
  store.newsSearchResultViewScrollPosition = 0
  store.newsSearchResult = []

  let userIdFromSession = sessionStorage.getItem("userId")
  try {
    let id = Number(userIdFromSession)
    console.log('userId from session', id);
    if (id == 0) {
      // 说明session storage里面没有用户id，需要重建
      console.log('userId need init', userId.value);
      sessionStorage.setItem('userId', userId.value.toString())
    }
    else {
      userId.value = id
    }
  } catch (error) {
  }

})

const router = useRouter()

const openChangeUserDialog = () => {
  // 同步userId的值
  userIdForVModel.value = userId.value
  dialogUserVisible.value = true

}

const registerConfirm = () => {
  console.log('confirm reg')
  request.get("/user/add/").then((response: any) => {
    // 注册成功之后
    console.log(response.data);

    // 切换用户
    userIdForVModel.value = response.data.id
    ElMessage(
      {
        message: '注册用户成功',
        type: 'success',
      })

    changeUserConfirm()


  })


}


const changeUserConfirm = () => {
  request.get("/user/find/" + userIdForVModel.value).then((response: any) => {
    // 确认此用户存在之后
    console.log(response.data, typeof (response.data));
    if (response.data != "" && response.data != null) {

      // 切换用户
      userId.value = userIdForVModel.value
      sessionStorage.clear()
      sessionStorage.setItem('userId', userId.value.toString())
      dialogUserVisible.value = false

      ElMessage(
        {
          message: '切换用户成功',
          type: 'success',
          duration: 500,
          onClose: () => {
            window.location.href = '/'
          }
        })

    }
    else {
      ElMessage(
        {
          message: '此用户不存在',
          type: 'error',
        })
    }
  })

}

const search = () => {
  if (keywords.value != '') {
    // 触发事件，要求搜索结果页面一定要刷新，避免keep alive的缓存影响
    store.changeKeywordsEvent()
    router.push("/search/" + keywords.value)

  }
  else {
    router.push("/")
  }
}


const gotoHome = () => {

  keywords.value = ''
  router.push("/")

}
</script>

<template>
  <div class="header-and-main">

    <div id=page class=not-login>
      <div id=appbar class=O>
        <div class="O-c b b-xc">
          <div class=O-status-vd></div>
          <div class=O-c-Q>

            <a @click="gotoHome()" class="O-j b-L">
              <div class=O-j-R><img src="/logo.png" sizes="1x1"></div>
              <div style="
                        margin-left: 15px;
                        display: inline; 
                        font-weight: bolder;
                        font-size: larger;">
                新闻推荐
              </div>
            </a>


          </div>
          <div class=I-J>
            <div class=I>
              <div class=I-form @keyup.enter="search()">
                <div @click="search()" class=I-n>
                  <i class=m-n></i>
                </div>
                <div class=I-K>
                  <input v-model="keywords" style="color: black;" class="I-K-L b-L" placeholder=搜索内容 autocomplete=off
                    value name=q>
                </div>
              </div>
            </div>
          </div>

          <div class="user-id">
            <div style="text-align: center;">
              <el-button @click="openChangeUserDialog()" class="user-id-text" type="" size="large" text bg plain>
                当前用户: {{ userId }}
              </el-button>
            </div>
          </div>
          <div class="user-id-mini">
            <div style="text-align: center;">

              <el-button @click="openChangeUserDialog()" class="user-id-text" type="" size="large" text bg plain>
                {{ userId }}
              </el-button>
            </div>
          </div>

          <div @click="openChangeUserDialog()" id=accounts-button class="S-T b-L">
            <img src="/aviator.png" class=account-i>
          </div>

        </div>
        <ul class="item-list sf-hidden">
        </ul>
      </div>
    </div>

    <div id=tabbar class="eb b-xc">
      <div class=kb-lb-ib>
        <div class=kb-lb-ib-hb>

        </div>

      </div>
    </div>

    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <keep-alive>
          <component :is="Component" />
        </keep-alive>
      </transition>
    </router-view>
  </div>




  <!-- <div class="footer" style="text-align: center; ">
    foot
  </div> -->

  <div class=scroller-status style="">
    <div class=infinite-scroll-last style="">
      <span class=loadmore-line></span>
      2023 NEU News-Recommender | Made with ❤
      <span class=loadmore-line></span>
    </div>
  </div>

  <el-dialog v-model="dialogUserVisible" title="切换用户" @submit.native.prevent>
    <template #default>
      <el-form>
        <el-form-item label="用户ID">
          <el-input @keyup.enter.native="changeUserConfirm()" v-model="userIdForVModel" autocomplete="off" />
        </el-form-item>
      </el-form>
      <el-dialog v-model="dialogRegisterVisible" width="30%" title="确定" append-to-body>
        确定注册吗？
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogRegisterVisible = false">取消</el-button>
            <el-button type="primary" @click="registerConfirm()">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </template>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogRegisterVisible = true" type="primary" style="float: left;">注册</el-button>
        <el-button @click="dialogUserVisible = false">取消</el-button>
        <el-button type="primary" @click="changeUserConfirm()">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
@media screen and (width <=730px) {

  /* 宽度 < 1000px时 */
  .user-id {
    display: none;
  }

  .user-id-mini {
    display: none;
  }
}

@media screen and (730px <=width <=1200px) {

  /* 730px < 宽度 < 1200px时 */
  .user-id {
    display: none;
  }

  .user-id-mini {
    display: inline;
    float: right;
    height: 30px;
    margin-right: 60px;
    ;
    margin-top: 14px;
    width: 15vw;
  }
}

@media screen and (min-width: 1200px) {

  /* 宽度 > 1200px时 */
  .user-id {
    display: inline;
    float: right;
    height: 30px;
    margin-right: 60px;
    ;
    margin-top: 14px;
    width: 15vw;
  }

  .user-id-mini {
    display: none;
  }
}

.user-id-text {
  font-size: 17px !important;
  position: relative;
  z-index: 9;
}

.user-id-text:hover {
  cursor: pointer;
}

.infinite-scroll-last {
  /* margin-top: 1000px; */
  /* top: 100px;; */
  padding-top: 1vh;
  padding-bottom: 1vh;
}

.scroller-status {
  /* 这行代码保证了无论右侧出现滚动条，footer都会是居中的 */
  margin-left: calc(100vw - 100%);
  /* width: 98%; */
  /* position: absolute; */
  /* margin: 20px auto; */
  /* padding: 20px 0; */
  min-height: 5vh;
  /* margin-bottom: -100px; */
  /* padding-bottom: 1px; */
  text-align: center;
  color: #999;
  font-size: 14px;
  clear: both;
  /* bottom: 1px; */
}

.loadmore-line {
  /* width: 120px; */
  width: 3vw;
  margin: 4px 10px;
  line-height: 1px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  display: inline-block
}

.header-and-main {
  min-height: 95vh;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.1s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
